package com.lw.leetcode.arr.b;

import java.util.Arrays;

/**
 * 542. 01 矩阵
 * 剑指 Offer II 107. 矩阵中的距离
 *
 * @Author liw
 * @Date 2021/6/24 16:54
 * @Version 1.0
 */
public class UpdateMatrix {

    public static void main(String[] args) {
        UpdateMatrix test = new UpdateMatrix();

        int[][] arr = {{0, 0, 0},
                {0, 1, 0},
                {0, 0, 0}};
        int[][] ints = test.updateMatrix(arr);
        for (int[] array : ints) {
            System.out.println(Arrays.toString(array));
        }
    }


    private int[][] mat;
    private int a;
    private int b;

    public int[][] updateMatrix(int[][] mat) {

        this.mat = mat;
        this.a = mat.length;
        this.b = mat[0].length;
        for (int i = 0; i < a; i++) {
            for (int j = 0; j < b; j++) {
                if (mat[i][j] == 0) {
                    find(i - 1, j, -1);
                    find(i + 1, j, -1);
                    find(i, j - 1, -1);
                    find(i, j + 1, -1);
                }
            }
        }
        for (int i = 0; i < a; i++) {
            for (int j = 0; j < b; j++) {
                if (mat[i][j] < 0) {
                    mat[i][j] = ~mat[i][j] + 1;
                }
            }
        }
        return mat;
    }

    private void find(int x, int y, int value) {
        if (x < 0 || y < 0 || x == a || y == b) {
            return;
        }
        int v = mat[x][y];
        if (v == 0) {
            return;
        }
        if (v == 1 || v < value) {
            mat[x][y] = value;
            value--;
            find(x - 1, y, value);
            find(x + 1, y, value);
            find(x, y - 1, value);
            find(x, y + 1, value);
        }
    }
}
